package com.sttk.fastMark.camera.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.sttk.fastMark.camera.BaseAc;
import com.sttk.fastMark.camera.Content;
import com.sttk.fastMark.camera.R;
import com.sttk.fastMark.camera.adapter.AlbumChildAdapter;
import com.sttk.fastMark.camera.adapter.PhoneAlbumAdapter;
import com.sttk.fastMark.camera.basic.picselect.MediaLoadManager;
import com.sttk.fastMark.camera.basic.picselect.PhotoConfig;
import com.sttk.fastMark.camera.basic.utils.RxUtil;
import com.sttk.fastMark.camera.bean.PhoneAlbumBean;
import com.sttk.fastMark.camera.databinding.ActivityAddPictureBinding;
import com.sttk.fastMark.camera.dialog.PermissionExplainDialog;
import com.sttk.fastMark.camera.utils.MyMediaLoader;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.core.ObservableEmitter;

public class AddPictureActivity extends BaseAc<ActivityAddPictureBinding> implements View.OnClickListener, OnItemClickListener, OnItemChildClickListener {

    private PhoneAlbumAdapter mPhoneAlbumAdapter;
    private List<String> listSel = new ArrayList<>();

    @Override
    protected int onCreate() {
        return R.layout.activity_add_picture;
    }

    @Override
    protected void initView() {
        mDataBinding.ivAddPictureBack.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.tvStart.setOnClickListener(this);

        mDataBinding.rvPictureList.setLayoutManager(new LinearLayoutManager(mContext));
        mPhoneAlbumAdapter = new PhoneAlbumAdapter();
        mDataBinding.rvPictureList.setAdapter(mPhoneAlbumAdapter);
        mPhoneAlbumAdapter.setEdit(true);
        mPhoneAlbumAdapter.addChildClickViewIds(R.id.llPhoneAlbumSelector);
        mPhoneAlbumAdapter.setOnItemClickListener(this);
        mPhoneAlbumAdapter.setOnItemChildClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tvStart) {//开始拼图
            if (listSel.size() == 0) {
                ToastUtils.showShort(getString(R.string.please_sel_picture));
                return;
            }
            Intent intent = new Intent();
            intent.putStringArrayListExtra(Content.list, (ArrayList<String>) listSel);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter instanceof AlbumChildAdapter) {
            AlbumChildAdapter albumChildAdapter = (AlbumChildAdapter) adapter;
            PhoneAlbumBean.ClassBean item = albumChildAdapter.getItem(position);
            item.setSelected(!item.isSelected());
            albumChildAdapter.notifyDataSetChanged();

            boolean isSelectAll = true;
            for (PhoneAlbumBean.ClassBean classBean : albumChildAdapter.getData()) {
                if (!classBean.isSelected()) {
                    isSelectAll = false;
                    break;
                }
            }
            PhoneAlbumBean phoneAlbumBean = albumChildAdapter.getPhoneAlbumBean();
            phoneAlbumBean.setSelected(isSelectAll);
            mPhoneAlbumAdapter.notifyDataSetChanged();

            if (item.isSelected()) {
                listSel.add(item.getPath());
            } else {
                listSel.remove(item.getPath());
            }
        }
        mDataBinding.tvStart.setText(getString(R.string.start_puzzle_num, listSel.size()));
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (view.getId() == R.id.llPhoneAlbumSelector) {
            PhoneAlbumBean item = mPhoneAlbumAdapter.getItem(position);
            item.setSelected(!item.isSelected());
            for (PhoneAlbumBean.ClassBean classBean : item.getClassBeanList()) {
                classBean.setSelected(item.isSelected());
            }
            mPhoneAlbumAdapter.notifyDataSetChanged();

            if (item.isSelected()) {
                for (PhoneAlbumBean.ClassBean classBean : item.getClassBeanList()) {
                    listSel.add(classBean.getPath());
                }
            } else {
                for (PhoneAlbumBean.ClassBean classBean : item.getClassBeanList()) {
                    listSel.remove(classBean.getPath());
                }
            }
        }
        mDataBinding.tvStart.setText(getString(R.string.start_puzzle_num, listSel.size()));
    }

    @Override
    protected void initData() {
        mDataBinding.tvStart.setText(getString(R.string.start_puzzle_num, 0));
        getPermission();
    }

    private void getPermission() {
        PermissionExplainDialog dialog = new PermissionExplainDialog(mContext);
        dialog.setContent(getString(R.string.get_picture_permission));
        List<String> permissionsInManifest = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissionsInManifest.add(Manifest.permission.READ_MEDIA_IMAGES);
            permissionsInManifest.add(Manifest.permission.READ_MEDIA_VIDEO);
        } else {
            permissionsInManifest.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            permissionsInManifest.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        PermissionUtils.permission(permissionsInManifest.toArray(new String[permissionsInManifest.size()])).explain(new PermissionUtils.OnExplainListener() {
            @Override
            public void explain(@NonNull UtilsTransActivity activity, @NonNull List<String> denied, @NonNull ShouldRequest shouldRequest) {
                dialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shouldRequest.start(true);
                    }
                }, 500);
            }
        }).callback(new PermissionUtils.SimpleCallback() {
            @Override
            public void onGranted() {
                dialog.dismiss();
                getData();
            }

            @Override
            public void onDenied() {
                dialog.dismiss();
            }
        }).request();
    }

    //获取视频和图片数据
    private void getData() {
        RxUtil.create(new RxUtil.Callback<List<PhoneAlbumBean>>() {
            @Override
            public void doBackground(ObservableEmitter<List<PhoneAlbumBean>> emitter) {
                List<PhoneAlbumBean> listSys = MyMediaLoader.getInstance().loadPicData(MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.PHOTO), true);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<PhoneAlbumBean> phoneAlbumBeans) {
                if (phoneAlbumBeans.size() > 0) {
                    mPhoneAlbumAdapter.setList(phoneAlbumBeans);
                    mDataBinding.rvPictureList.setVisibility(View.VISIBLE);
                    mDataBinding.flPictureNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvPictureList.setVisibility(View.GONE);
                    mDataBinding.flPictureNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }
}